//
//  TZScrollViewController.m
//  iOS-CtrlV
//
//  Created by Wang Li on 13-3-15.
//  Copyright (c) 2013年 Wang Li. All rights reserved.
//

#import "TZScrollViewController.h"
#import "MainTabBarController.h"
#import "ASIHTTPRequest.h"
#import "CJSONDeserializer.h"
@interface TZScrollViewController ()

@end

@implementation TZScrollViewController
@synthesize m_DetailID;
- (id)init
{
    if (self = [super init]) {
        // Custom initialization
        _AllTieIDArr = [[NSMutableArray alloc] init];
    }
    return self;
}

-(void) dealloc
{
    [_AllTieIDArr release];
    [_HScrollView release];
    [m_DetailID release];
    [_BackBttBarItem release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor colorWithRed:193/255.f green:193/255.f blue:193/255.f alpha:1]];
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    if([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] ) {
        [self.navigationController.navigationBar setBackgroundImage:tAppDel.m_MidNavImg forBarMetrics: UIBarMetricsDefault];
        self.navigationController.navigationBar.clipsToBounds = NO;
    }
    
	// Do any additional setup after loading the view.
    _BackBttBarItem =[UIButton buttonWithType:UIButtonTypeCustom];
    _BackBttBarItem.frame =CGRectMake(0, 0, 44, 44);
    [_BackBttBarItem setImage:[UIImage imageNamed:@"navback.png"] forState:UIControlStateNormal];
    [_BackBttBarItem addTarget:self action:@selector(navBackBtt) forControlEvents:UIControlEventTouchUpInside];
    [_BackBttBarItem retain];
    [self.navigationController.navigationBar addSubview:_BackBttBarItem];
    
    
    _HScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 480-20-44)];
    _HScrollView.pagingEnabled = YES;
    _HScrollView.delegate = self;
    [self.view addSubview:_HScrollView];
    
    
    [self requestDetail];
}

-(void) setScrollView
{
    [_HScrollView setContentSize:CGSizeMake(320*[_AllTieIDArr count], _HScrollView.frame.size.height)];
    int tIndexTag = 0;
    for (NSString* tIds in _AllTieIDArr) {
        if ([m_DetailID isEqualToString:tIds]) {
            break;
        }
        tIndexTag++;
    }
    
    TZDetailViewController* tTZDetailVC = [[TZDetailViewController alloc] initWithFrame:CGRectMake(tIndexTag*320, 0, 320, 480-20-44)];
    tTZDetailVC.m_MainTabBar =(MainTabBarController*)self.navigationController.tabBarController;
    tTZDetailVC.m_ViewController = self;
    tTZDetailVC.m_DetailID =m_DetailID;
    _HScrollView.showsHorizontalScrollIndicator = NO;
    _HScrollView.showsVerticalScrollIndicator =NO;
    tTZDetailVC.tag = 10000+tIndexTag;
    [_HScrollView addSubview:tTZDetailVC];
    [tTZDetailVC requestDetail];
    [tTZDetailVC release];
    
    [_HScrollView scrollRectToVisible:tTZDetailVC.frame animated:NO];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void) viewWillDisappear:(BOOL)animated
{
    [_BackBttBarItem removeFromSuperview];
}

-(void) viewWillAppear:(BOOL)animated
{
    if ([_BackBttBarItem superview] ==nil) {
        [self.navigationController.navigationBar addSubview:_BackBttBarItem];
    }
}

-(void) navBackBtt
{
    [_BackBttBarItem removeFromSuperview];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    int tCountRightX =scrollView.contentOffset.x+320+160;
    int tCountLeftX =scrollView.contentOffset.x-160;
    int tNextPage = -1;
    int tLastPage = -1;
    //NSLog(@"%d",tCountLeftX);
    if (tCountRightX <= scrollView.contentSize.width) {
        tNextPage = (tCountRightX-320)/320;
    }
    if (tCountLeftX >= 0) {
        tLastPage = tCountRightX/320;
    }
    if (tNextPage >= 1) {
        if ([_HScrollView viewWithTag:1000+tNextPage] == nil) {
            TZDetailViewController* tTZDetailVC = [[TZDetailViewController alloc] initWithFrame:CGRectMake((tNextPage-1)*320, 0, 320, 480-20-44)];
            tTZDetailVC.m_MainTabBar =(MainTabBarController*)self.navigationController.tabBarController;
            tTZDetailVC.m_ViewController = self;
            tTZDetailVC.m_DetailID =[_AllTieIDArr objectAtIndex:tNextPage-1];
            tTZDetailVC.tag = 1000+tNextPage;
            [_HScrollView addSubview:tTZDetailVC];
            [tTZDetailVC requestDetail];
            [tTZDetailVC release];
        }
    }
    
    if (tLastPage >= 1) {
        if ([_HScrollView viewWithTag:1000+tLastPage] == nil) {
            TZDetailViewController* tTZDetailVC = [[TZDetailViewController alloc] initWithFrame:CGRectMake((tLastPage-1)*320, 0, 320, 480-20-44)];
            tTZDetailVC.m_MainTabBar =(MainTabBarController*)self.navigationController.tabBarController;
            tTZDetailVC.m_ViewController = self;
            tTZDetailVC.m_DetailID =[_AllTieIDArr objectAtIndex:tLastPage-1];
            tTZDetailVC.tag = 1000+tLastPage;
            [_HScrollView addSubview:tTZDetailVC];
            [tTZDetailVC requestDetail];
            [tTZDetailVC release];
        }
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    
}



-(void) tellSupperCurrent:(int)f_Current TotallNum:(int)f_Totall
{
//    [_HScrollView setContentSize:CGSizeMake(320*f_Totall, _HScrollView.frame.size.height)];
//    TZDetailViewController* tTZDetailVC =(TZDetailViewController*)[_HScrollView viewWithTag:-100];
//    tTZDetailVC.tag = 10000+f_Current-1;
//    CGRect aframe = tTZDetailVC.frame;
//    aframe.origin.x = (f_Current-1)*320;
//    tTZDetailVC.frame = aframe;
//    [_HScrollView scrollRectToVisible:aframe animated:NO];
}


#pragma mark -
#pragma mark MBProgressHUDDelegate
- (void)hudWasHidden:(MBProgressHUD *)hud{
    p_MBHUD.delegate = nil;
	[p_MBHUD removeFromSuperview];
	[p_MBHUD release];
	p_MBHUD=nil;
}

-(void) addHudLoad{
	if (p_MBHUD == nil) {
		p_MBHUD = [[MBProgressHUD alloc] initWithView:self.view];
		// Add HUD to screen
		[self.navigationController.view addSubview:p_MBHUD];
		// Regisete for HUD callbacks so we can remove it from the window at the right time
		p_MBHUD.delegate = self;
		p_MBHUD.labelText = @"请求数据中...";
		[p_MBHUD show:YES];
	}
}



-(void) requestDetail
{
    [self addHudLoad];
    NSURL* tRequestURL =nil;
    MainTabBarController* tMainTabBar = (MainTabBarController*)self.navigationController.tabBarController;
    if (tMainTabBar.m_UserDic != nil) {
        tRequestURL =[NSURL URLWithString:[NSString stringWithFormat:@"%@?app=blog&act=detail&id=%@&user_id=%@",RequestMainURL,m_DetailID,[tMainTabBar.m_UserDic objectForKey:@"user_id"]]];
    }else{
        tRequestURL =[NSURL URLWithString:[NSString stringWithFormat:@"%@?app=blog&act=detail&id=%@",RequestMainURL,m_DetailID]];
    }

    ASIHTTPRequest* tRequestSearchNum = [ASIHTTPRequest requestWithURL:tRequestURL];
    [tRequestSearchNum setDelegate:self];
    [tRequestSearchNum setDidFinishSelector:@selector(requestTZDetailFinish:)];
    [tRequestSearchNum startAsynchronous];
}
- (void)requestTZDetailFinish:(ASIHTTPRequest *)request;
{
    NSError* tError;
    
    NSString* tReqStr = [request responseString];
    NSLog(@"ads json data =%@",[request responseString]);
    NSData *jsonData = [tReqStr dataUsingEncoding:NSUTF32BigEndianStringEncoding];
    NSDictionary *tDictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&tError] ;
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    if (tDictionary == nil) {
        [tAppDel showWithCustomView:@"提示" detailText:@"获得数据错误" isCue:YES delayTime:3.0f];
        [self hudWasHidden:nil];
        return;
    }
    int tErrorCode= [[tDictionary objectForKey:@"errorCode"] intValue];
    if (tErrorCode != 0) {
        [tAppDel showWithCustomView:@"提示" detailText:[tDictionary objectForKey:@"errorMsg"] isCue:YES delayTime:3.0f];
        [self hudWasHidden:nil];
        return;
    }

    NSDictionary* tDataDic = [tDictionary objectForKey:@"data"];
    NSString* tIDsStr = [tDataDic objectForKey:@"all_ids"];
    NSArray* tIDsArr = [tIDsStr componentsSeparatedByString:@","];
    [_AllTieIDArr removeAllObjects];
    [_AllTieIDArr addObjectsFromArray:tIDsArr];
    [self setScrollView];
    
    [self hudWasHidden:nil];
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    [self hudWasHidden:nil];
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [tAppDel showWithCustomView:@"提示" detailText:@"网络错误请稍后再试" isCue:YES delayTime:3.0f];
}
@end
